package bat.ke.qq.com.tx;

import bat.ke.qq.com.AppConfig;
import bat.ke.qq.com.service.UserSerivce;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.naming.Context;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Spring实现事务的逻辑：动态代理生成代理对象，实现增强逻辑。
 */
public class TransactionExample {

    public static void main(String[] args) {
//        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-tx.xml");
//        final UserSerivce userSerivce = context.getBean(UserSerivce.class);
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AppConfig.class);
        UserSerivce userSerivce = (UserSerivce) applicationContext.getBean("userService");
        UserSerivce proxyUserSerivce = (UserSerivce) Proxy.newProxyInstance(
                TransactionExample.class.getClassLoader(),
                new Class[]{UserSerivce.class},
                new TransactionHandler(userSerivce));
        try {
            proxyUserSerivce.createUser("hujunjie");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    static class TransactionHandler implements InvocationHandler {

        private Object object;

        public TransactionHandler(Object object) {
            this.object = object;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            try {
                System.out.println("开启事物:" + method.getName());
                return method.invoke(object, args);
            } finally {
                System.out.println("关闭事物:" + method.getName());
            }
        }
    }
}
